﻿using UnityEngine;
using UnityEngine.UI;
using LitJson;
using System.Text.RegularExpressions;
using System.Net;

public class JoinRoomLayer : MonoBehaviour
{
    private static JoinRoomLayer m_Inst;
    public static JoinRoomLayer Instance
    {
        get { return m_Inst; }
    }

    public Button m_BtnClose;

    public CanvasGroup m_CgrpServer;
    public InputField m_IptServerIp;
    public InputField m_IptServerPort;
    public Button m_BtnClient;

    public InputField m_IptJoinKey;
    public Button m_BtnJoin;

    public Text m_TxtTips;

    private JsonData m_JoinNotiData;

    public JoinRoomLayer()
    {
        if (null == m_Inst)
            m_Inst = this;
        else
            Debug.LogError($"{GetType().Name}: multi Inst");
    }

    private void OnDestroy()
    {
        if (this == m_Inst) m_Inst = null;
        RegistMsg(false);
    }

    void Start()
    {
        m_BtnClose.onClick.AddListener(OnClick_Close);
        m_BtnClient.onClick.AddListener(OnClick_Client);
        m_BtnJoin.onClick.AddListener(OnClick_Join);
    }

    void OnEnable()
    {
        RegistMsg(true);

        m_IptJoinKey.text = "";
        var tipsText = "";

        bool isNeedConnect = false;
        if (null == NetManager.Instance.ClientConn)
        {
            isNeedConnect = true;
        }
        else
        {
            switch (NetManager.Instance.ClientConn.connectStatus)
            {
            case MyTcpClientConn.ConnectStatus.Begin:
                m_CgrpServer.interactable = false;
                m_BtnClient.GetComponentInChildren<Text>().text = "连接中...";
                break;
            case MyTcpClientConn.ConnectStatus.Connected:
                //m_IptServerIp.text = "";
                //m_IptServerPort.text = "";
                m_CgrpServer.interactable = false;
                m_BtnClient.GetComponentInChildren<Text>().text = "断开连接";
                break;
            case MyTcpClientConn.ConnectStatus.Disconnect:
                isNeedConnect = true;
                break;
            }
        }

        if (isNeedConnect)
        {
            m_IptServerIp.text = PlayerPrefs.GetString("ServerIp", "");
            m_IptServerPort.text = PlayerPrefs.GetString("ServerPort", "");
            m_CgrpServer.interactable = true;
            m_BtnClient.GetComponentInChildren<Text>().text = "连接主机";
        }
        //todo: 是否已加入

        m_TxtTips.text = "";
    }

    private void OnDisable()
    {
        RegistMsg(false);
    }

    private void OnClick_Close()
    {
        this.gameObject.SetActive(false);
    }

    private void OnClick_Join()
    {
        if ("" == m_IptJoinKey.text)
        {
            m_TxtTips.text = "密令为空";
            return;
        }
        if (!int.TryParse(m_IptJoinKey.text, out var result) || 4 != m_IptJoinKey.text.Length)
        {
            m_TxtTips.text = "密令为4位数字";
            return;
        }

        if (null == NetManager.Instance.ClientConn || MyTcpClientConn.ConnectStatus.Disconnect == NetManager.Instance.ClientConn.connectStatus)
        {
            m_TxtTips.text = "还未连接主机";
            return;
        }
        m_TxtTips.text = "";

        var socketData = new JsonData();
        socketData["msg"] = "Join";
        socketData["key"] = m_IptJoinKey.text;
        NetManager.Instance.m_ClientConn.Send(socketData.ToJson());
    }

    private void OnClick_Client()
    {
        bool isCreate = false;
        if (null == NetManager.Instance.ClientConn)
        {
            isCreate = true;
        }
        else
        {
            switch (NetManager.Instance.ClientConn.connectStatus)
            {
            case MyTcpClientConn.ConnectStatus.Begin:
                Debug.Log("connecting");
                return;
            case MyTcpClientConn.ConnectStatus.Connected:
                NetManager.Instance.ClientConn.Stop();
                m_CgrpServer.interactable = true;
                m_BtnClient.GetComponentInChildren<Text>().text = "连接主机";
                return;
            case MyTcpClientConn.ConnectStatus.Disconnect:
                if (!NetManager.Instance.ClientConn.IsStopped) //stopping中
                    isCreate = true;
                break;
            }
        }

        //IsStopping && !IsStopped

        if (!CheckIpInput(m_IptServerIp.text)) return;
        if (!int.TryParse(m_IptServerPort.text, out var port) || port <= 0 || port > 65535)
        {
            m_TxtTips.text = "端口格式错误：范围[1, 65535]";
            return;
        }
        m_TxtTips.text = "";

        var serverIp = IPAddress.Parse(m_IptServerIp.text);
        var serverAddress = new IPEndPoint(serverIp, port);

        if (isCreate)
            NetManager.Instance.CreateClientConn();

        NetManager.Instance.ClientConnect(serverAddress);
        m_CgrpServer.interactable = false;
        m_BtnClient.GetComponentInChildren<Text>().text = "连接中...";
    }

    public bool CheckIpInput(string ipAddress)
    {
        if (string.IsNullOrEmpty(ipAddress))
        {
            m_TxtTips.text = "IP地址为空";
            return false;
        }
        var pattern = @"^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$";
        //var regex = new Regex(pattern);
        //return regex.IsMatch(ipAddress.Trim());
        if (!Regex.IsMatch(ipAddress.Trim(), pattern))
        {
            m_TxtTips.text = "IP地址格式错误";
            return false;
        }
        return true;
    }

    //******************** message

    private void RegistMsg(bool b)
    {
        if (b)
        {
            MsgDispatch.Instance.AddReceiver("Client.ConnectFail", OnMsg_ConnectFail);
            MsgDispatch.Instance.AddReceiver("Client.Connected", OnMsg_Connected);
            MsgDispatch.Instance.AddReceiver("Client.Disconnect", OnMsg_Disconnect);
            MsgDispatch.Instance.AddReceiver("Join", OnMsg_Join);
            MsgDispatch.Instance.AddReceiver("JoinNoti", OnMsg_JoinNoti);
        }
        else
        {
            MsgDispatch.Instance.RemoveReceivers(this);
        }
    }

    public void OnMsg_ConnectFail(string msg, object obj)
    {
        m_CgrpServer.interactable = true;
        m_BtnClient.GetComponentInChildren<Text>().text = "连接主机";
        m_TxtTips.text = "连接失败";
    }

    public void OnMsg_Connected(string msg, object obj)
    {
        m_CgrpServer.interactable = false;
        m_BtnClient.GetComponentInChildren<Text>().text = "断开连接";
    }

    public void OnMsg_Disconnect(string msg, object obj) //与服务器断开
    {
        m_CgrpServer.interactable = true;
        m_BtnClient.GetComponentInChildren<Text>().text = "连接主机";
    }

    public void OnMsg_Join(string msg, object obj)
    {
        var data = (JsonData)obj;
        int code = (int)data["code"];
        if (0 == code)
        {
            PlayerPrefs.SetString("ServerIp", m_IptServerIp.text);
            PlayerPrefs.SetString("ServerPort", m_IptServerPort.text);
            //密令对了
            this.gameObject.SetActive(false); //界面关闭
            StartLayer.Instance.gameObject.SetActive(false);
            GoBangController_Tcp.Instance.m_SelfIsServer = false;
            GoBangController_Tcp.Instance.m_GameKey = m_IptJoinKey.text;
            GoBangTest.Instance.m_Controller = GoBangController_Tcp.Instance;
            GoBangTest.Instance.gameObject.SetActive(true);
        }
        else if (1 == code)
        {
            m_TxtTips.text = "密令错误!";
        }
        else if (2 == code)
        {
            m_TxtTips.text = "棋局还未创建!";
        }
    }

    public void OnMsg_JoinNoti(string msg, object obj)
    {

    }

    //********************

}
